package com.ts.api.module.api.entity.bo;

import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.RequestHeader;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.constant.api.ApiServiceCodeEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.module.api.entity.po.ApiLogPO;
import lombok.Data;

/**
 * @author Pan
 */
@Data
public class ApiHeaderBO {

    /** 客户端id */
    private String clientId;
    /** 时间 */
    private String timestamp;
    /** 签名 */
    private String sign;
    /** 业务编码 */
    private String serviceCode;

    public ApiHeaderBO() {
        super();
    }

    public ApiHeaderBO(String clientId, String timestamp, String sign, String serviceCode) {
        this.clientId = clientId;
        this.timestamp = timestamp;
        this.sign = sign;
        this.serviceCode = serviceCode;
    }

    /**
     * 校验基本参数
     *
     * @return boolean
     */
    public ApiHeaderBO valid() {
        Assert.isTrue(ValidParam.requiredBean(this), () -> { throw new ApiMsgException(ApiEnum.API_HEADER_ERROR); });
        Assert.isFalse(ApiServiceCodeEnum.get(this.serviceCode) == null, () -> { throw new ApiMsgException(ApiEnum.API_SERVICE_CODE_ERROR); });

        Long time = null;
        try {
            time = Long.valueOf(this.getTimestamp());
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_HEADER_TIME_ERROR);
        }
        //  五分钟校验
        Assert.isFalse(DateUtils.nowExpiredMillisInMinutes(5, time), () -> {throw new ApiMsgException(ApiEnum.API_HEADER_EXPIRE);});
        return this;
    }

    public static ApiHeaderBO createBO(RequestHeader requestHeader) {
        //  记录业务信息
        ApiLogPO logPO = ApiContext.LOG_OBJECT.get();
        logPO.setApiClientId(requestHeader.get("client-id"));
        logPO.setEventType(requestHeader.get("service-code"));

        return new ApiHeaderBO(requestHeader.get("client-id"), requestHeader.get("timestamp"), requestHeader.get("sign"), requestHeader.get("service-code"));
    }
}
